import './WijmoB03.scss'
import { useMount, useReactive } from "ahooks";
import { useState } from "react";

import { showPopup, hidePopup, hasClass, contains, closest, createElement, getElement, removeChild } from '@grapecity/wijmo';
import { ListBox } from '@grapecity/wijmo.react.input';
import { FlexGrid } from '@grapecity/wijmo.react.grid';
import { Button, Switch } from 'antd';


const WijmoB03 = () => {

    const InitData = useReactive({
        columnPicker: null,
        isDragEnabled: false,
        flex: null,
        dragSrc: null,
        dragDst: null
    })

    const [Data, setData] = useState()
    useMount(() => {
        const countries = ['US', 'Germany', 'UK', 'Japan', 'Italy', 'Greece'],
            products = ['Widget', 'Sprocket', 'Gadget', 'Doohickey'],
            colors = ['Black', 'White', 'Red', 'Green', 'Blue'],
            dt = new Date()
        const data = [...Array(24)].map((_, i) => {
            const date = new Date(dt.getFullYear(), i % 12, 25, i % 24, i % 60, i % 60),
                countryId = Math.floor(Math.random() * countries.length),
                productId = Math.floor(Math.random() * products.length),
                colorId = Math.floor(Math.random() * colors.length);
            return {
                id: i + 1,
                start: date,
                end: date,
                country: countries[countryId],
                product: products[productId],
                color: colors[colorId],
                countryId: countryId,
                productId: productId,
                colorId: colorId,
                amount1: Math.random() * 10000 - 5000,
                amount2: Math.random() * 10000 - 5000,
                amount3: Math.random() * 10000 - 5000,
                amount4: Math.random() * 10000 - 5000,
                amount5: Math.random() * 10000 - 5000,
                discount: Math.random() / 4,
                active: i % 4 == 0
            }
        })
        setData(data)
    })

    const init = (init) => {
        InitData.flex = init
        init.formatItem.addHandler((s, e) => {
            if (e.panel === s.topLeftCells) {
                e.cell.innerHTML = '<span class="column-picker-icon glyphicon glyphicon-cog">头</span>'
            }
        });
        const ref = init.hostElement.querySelector(".wj-topleft")

        ref.addEventListener("mousedown", e => {
            if (hasClass(e.target, "column-picker-icon")) {
                let host = InitData.columnPicker.hostElement
                console.log(host)
                if (!host.offsetHeight) {
                    showPopup(host, ref, false, true, false)
                    InitData.columnPicker.focus()
                }
                else {
                    hidePopup(host, true, true)
                    InitData.flex.focus()
                }
                InitData.columnPicker.focus()
                e.preventDefault()
            }
        });
        window.addEventListener('touchstart', (e) => {
            let host = InitData.columnPicker.hostElement
            if (!contains(host, e.target) && !closest(e.target, '.wj-flexgrid')) hidePopup(host, true, true)
        })
    }

    const initialized = (init) => {
        const host = init.hostElement
        host.addEventListener('dragstart', handleDragStart);
        host.addEventListener('dragover', handleDragOver);
        host.addEventListener('drop', handleDrop);
        host.addEventListener('dragend', handleDragEnd);
        InitData.columnPicker = init
        if (InitData.flex) {
            InitData.columnPicker.itemsSource = InitData.flex.columns;
            InitData.columnPicker.checkedMemberPath = 'visible';
            InitData.columnPicker.displayMemberPath = 'header';
            InitData.columnPicker.lostFocus.addHandler(() => {
                hidePopup(InitData.columnPicker.hostElement);
            });
            InitData.columnPicker.formatItem.addHandler((s, e) => {
                enableDragItem(e.item, InitData.isDragEnabled);
            });
        }
    }

    const handleDragStart = (e) => {
        InitData.dragSrc = closest(e.target, '.wj-listbox-item')
        if (InitData.dragSrc) {
            e.dataTransfer.setData('text', InitData.dragSrc.innerHTML)
            e.dataTransfer.effectAllowed = 'move';
        }
    }

    const handleDragOver = (e) => {
        const dragOver = closest(e.target, '.wj-listbox-item')
        if (InitData.dragDst && InitData.dragDst !== dragOver) removeDropMarker()
        if (dragOver && dragOver !== InitData.dragSrc) {
            e.preventDefault()
            e.dataTransfer.dropEffect = 'move'
            InitData.dragDst = dragOver
            const src = getElementIndex(InitData.dragSrc);
            const dst = getElementIndex(InitData.dragDst);
            removeDropMarker();
            addDropMarker(dst > src);
        }
        else InitData.dragDst = null

    }
    const handleDrop = (e) => {
        if (InitData.dragSrc && InitData.dragDst) {
            e.preventDefault();
            const src = getElementIndex(InitData.dragSrc);
            const dst = getElementIndex(InitData.dragDst);
            InitData.flex.columns.moveElement(src, dst);
        }
    }
    const handleDragEnd = () => {
        InitData.dragSrc = null
        InitData.dragDst = null
        removeDropMarker()
    }

    const saveLayout = () => {
        localStorage.setItem("myLayout", InitData.flex.columnLayout);
    }
    const loadLayout = () => {
        let layout = localStorage.getItem("myLayout");
        if (layout) InitData.flex.columnLayout = layout;
    }

    const enableDrag = (e) => {
        InitData.isDragEnabled = e
        const host = InitData.columnPicker.hostElement;
        const items = host.getElementsByClassName('wj-listbox-item');
        for (let i = 0; i < items.length; i++) {
            enableDragItem(items[i], InitData.isDragEnabled);
        }
    }

    const enableDragItem = (item, enabled) => {
        item.setAttribute('draggable', enabled.toString())
    }
    const removeDropMarker = () => {
        removeChild(getElement('.drop-marker'));
    }
    const getElementIndex = (element) => {
        const parent = element.parentElement;
        const siblings = Array.prototype.slice.call(parent.children);
        return siblings.indexOf(element);
    }

    const addDropMarker = (isAfterPos) => {
        const itemsGap = 10;
        const width = 6;
        const margin = itemsGap / width;
        const height = InitData.dragDst.clientHeight;
        const topPos = InitData.dragDst.offsetTop;
        const leftPos = isAfterPos
            ? (InitData.dragDst.offsetLeft + InitData.dragDst.clientWidth + margin)
            : (InitData.dragDst.offsetLeft - itemsGap + margin);
        const css = `top:${topPos}px;left:${leftPos}px;height:${height}px;width:${width}px`
        const html = `<div class="drop-marker" style="${css}">&nbsp</div>`
        createElement(html, InitData.columnPicker.hostElement)
    }

    if (Data) {
        return (
            <div className='Page WijmoB03 '>
                <FlexGrid initialized={init} itemsSource={Data} />
                <div className="column-picker-div">
                    <ListBox className="column-picker" initialized={initialized} />
                </div>
                <div>
                    <Switch onChange={enableDrag} />
                    <Button onClick={saveLayout}>保存布局</Button>
                    <Button onClick={loadLayout}>恢复布局</Button>
                </div>
                <div>头部切换</div>
                <div>布局保存&恢复</div>
            </div>
        );
    }


};

export default WijmoB03;